using System.Text.Json;
using System.Text;
using RabbitMQ.Client;

namespace Beauty.Net.RabbitMQ
{
    /// <summary>
    /// RabbitMQ生产者接口
    /// </summary>
    public interface IRabbitMQProducer
    {
        /// <summary>
        /// 发布消息
        /// </summary>
        void Publish<T>(string exchange, string routingKey, T message, bool persistent = true);

        /// <summary>
        /// 发布消息（带属性）
        /// </summary>
        void Publish<T>(string exchange, string routingKey, T message, Dictionary<string, object> headers, bool persistent = true);
    }

    /// <summary>
    /// RabbitMQ生产者基类
    /// </summary>
    public abstract class RabbitMQProducerBase : IRabbitMQProducer
    {
        protected readonly IRabbitMQConnectionManager _connectionManager;
        protected readonly JsonSerializerOptions _jsonOptions;

        protected RabbitMQProducerBase(IRabbitMQConnectionManager connectionManager)
        {
            _connectionManager = connectionManager;
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = false
            };
        }

        public virtual void Publish<T>(string exchange, string routingKey, T message, bool persistent = true)
        {
            Publish(exchange, routingKey, message, new Dictionary<string, object>(), persistent);
        }

        public virtual void Publish<T>(string exchange, string routingKey, T message, Dictionary<string, object> headers, bool persistent = true)
        {
            using (var channel = _connectionManager.CreateChannel())
            {
                var properties = channel.CreateBasicProperties();
                properties.Persistent = persistent;

                if (headers != null && headers.Count > 0)
                {
                    properties.Headers = headers;
                }

                var messageBody = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message, _jsonOptions));
                channel.BasicPublish(exchange, routingKey, properties, messageBody);
            }
        }
    }
}